package com.campus.controller;


import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.campus.common.config.CodeConfig;
import com.campus.entity.Clazz.Clazz;
import com.campus.entity.Clazz.ClazzTeacher;
import com.campus.entity.ResultBody;
import com.campus.entity.Teacher;
import com.campus.entity.vo.Clazz.ClazzVO;
import com.campus.entity.vo.Teacher.TeacherVO;
import com.campus.service.ClazzService;
import com.campus.service.ClazzTeacherService;
import com.campus.service.TeacherService;
import com.campus.util.CopyPropertiesUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 教师表 前端控制器
 * </p>
 *
 * @author Alaskaboo
 * @since 2022-10-23 14:42:37
 */
@RestController
@RequestMapping("/api/teacher")
public class TeacherController {
    @Autowired
    private TeacherService teacherService;
    @Autowired
    private ClazzService clazzService;
    @Autowired
    private ClazzTeacherService clazzTeacherService;

    /**
     * 添加或者修改
     *
     * @param teacher
     * @return
     */
    @PostMapping
    @CacheEvict(value = "teacherInfo", allEntries =true)
    public ResultBody save(@RequestBody Teacher teacher) {
        if (teacher.getId() == null || teacher.getId() == -1) {
            teacherService.save(teacher);
        } else {
            teacherService.updateById(teacher);
        }
        return ResultBody.ok().data("teacher",teacher).message(CodeConfig.SUCCESS.message);
    }

    /**
     * 根据教师ID查询班级
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    @Cacheable(value = "teacherInfo", key = "#id")
    public ResultBody selectTeacherById(@PathVariable Long id) {
        Teacher teacherInfo = teacherService.getById(id);
        copeVo(teacherInfo);
        return ResultBody.ok().data("teacherInfo", teacherInfo);
    }

    /**
     * 根据老师Account查询
     *
     * @param account
     * @return
     */
    @RequestMapping("/info/{account}")
    @Cacheable(value = "teacherInfo", key = "#account")
    public ResultBody selectByAccount(@PathVariable String account) {
        Teacher teacherInfo = teacherService.lambdaQuery().in(Teacher::getAccount, account).one();
        if (teacherInfo == null) {
            return ResultBody.error(CodeConfig.QUERY_FAIL);
        }
        copeVo(teacherInfo);
        return ResultBody.ok().data("teacherInfo", teacherInfo).message(CodeConfig.QUERY_SUCCESS.message);
    }

    private void copeVo(Teacher teacherInfo) {
        TeacherVO teacherVO = new TeacherVO();
        BeanUtil.copyProperties(teacherInfo, teacherVO);
        queryTeacher(teacherVO, teacherInfo.getId(), teacherInfo);
    }

    private void queryTeacher(TeacherVO teacherVO, Long id, Teacher teacherInfo) {
        List<Clazz> clazzInfo = clazzService.list(new QueryWrapper<Clazz>().inSql("id", "select class_id from t_clazz_teacher where teacher_id=" + id));
        List<ClazzVO> collect = clazzInfo.stream().map(clazz -> CopyPropertiesUtils.copyProperties(clazz, ClazzVO.class)).collect(Collectors.toList());
        teacherVO.setClazzList(collect);
    }

    /**
     * 查询所有学生
     *
     * @param currentPage
     * @param pageSize
     * @param teacher
     * @return
     */
    @GetMapping("/{currentPage}/{pageSize}")
    @Cacheable(value = "teacherInfo", key="teacherInfo")
    public ResultBody selectStudentList(@PathVariable int currentPage, @PathVariable int pageSize, Teacher teacher) {
        Page<Teacher> teacherPage = new Page<>(currentPage, pageSize);
        //分页
        IPage<TeacherVO> teacherInfo = teacherService.selectTeacherList(teacherPage, teacher);
        List<TeacherVO> teacherList = teacherInfo.getRecords();
        for (TeacherVO teacher1 : teacherList) {
            queryTeacher(teacher1, teacher1.getId(), teacher);
        }
        //如果当前页码值大于了总页码值，那么重新执行查询操作，使用最大页码值作为当前页码值
        if (teacherInfo.getTotal() > 0) {
            return ResultBody.ok().data("teacherInfo", teacherInfo).message(CodeConfig.QUERY_SUCCESS.message);
        }
        return ResultBody.error().message(CodeConfig.QUERY_FAIL.message);
    }


    /**
     * 通过ids删除
     *
     * @param ids
     * @return
     */
    @DeleteMapping
    @CacheEvict(value = "teacherInfo", allEntries =true)
    public ResultBody deleteStudentByIds(Long[] ids) {
        try {
            teacherService.removeByIds(Arrays.asList(ids));
            clazzTeacherService.remove(new QueryWrapper<ClazzTeacher>().in("teacher_id", ids));
        } catch (Exception e) {
            e.printStackTrace();
            return ResultBody.error();
        }
        return ResultBody.ok().message(CodeConfig.DELETE_USER.message);
    }

    /**
     * 老师加入班级
     *
     * @param id
     * @param school
     * @param classNum
     * @return
     */
    @PostMapping("/join/{id}")
    @CacheEvict(value = "teacherInfo", allEntries =true)
    public ResultBody joinClazzStudent(@PathVariable(value = "id") Long id, String school, Integer classNum) {
        // 1. 通过school和classNum确定唯一数据
        Clazz clazz = clazzService.lambdaQuery().eq(Clazz::getSchool, school).eq(Clazz::getClassNum, classNum).one();
        //数据库无数据
        if (clazz == null) {
            return ResultBody.error().message(CodeConfig.Clazz_NOTFOUND.message);
        }
        // 2.比较用户输入和Clazz数据库表
        Long count = clazzTeacherService.lambdaQuery().eq(ClazzTeacher::getTeacherId, id).eq(ClazzTeacher::getClassId, clazz.getId()).count();
        if (count > 0) {
            return ResultBody.error().message(CodeConfig.JOIN_FAIL.message);
        }
        //校验成功写入数据库
        ClazzTeacher clazzTeacher = new ClazzTeacher();
        clazzTeacher.setTeacherId(id);
        clazzTeacher.setClassId(Long.valueOf(clazz.getId()));
        clazzTeacherService.save(clazzTeacher);
        return ResultBody.ok().data("clazzTeacher", clazzTeacher);
    }
}
